package cn.com.fssg.platform.base.handler.impl.gsl.jc;

import cn.com.fssg.platform.base.handler.InterfaceHandler;
import cn.com.fssg.platform.biz.BizUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Description: 工商联届次信息插入数据接口
 */
@Component
public class GslJcInsertCtl implements InterfaceHandler {

    private NamedParameterJdbcTemplate jdbcTemplate = BizUtil.cur().tenantMainJdbcTemplate();
//    @Autowired
//    private NamedParameterJdbcTemplate jdbcTemplate;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object run(HttpServletRequest request, JSONObject jsonObject) throws Exception {
        String gslJcId = jsonObject.getString("id");
        //验证届次是否存在
        String querySql = "select * from gsl_jc where id = :id";
        Map<String, Object> params = new HashMap<>();
        params.put("id", gslJcId);
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(querySql, params);
        //执委ID
        JSONArray jsonarray = jsonObject.getJSONArray("zwIdList");
        List<Integer> jcZwCount = new ArrayList<>();
        if (maps.isEmpty()) {
            jsonarray.forEach(s -> {
                String wxUserId = (String) s;
                String wxNewUserId = BizUtil.cur().getSnowflakeIdStr();
                //添加执委wx_user
                saveWxUser(wxUserId, wxNewUserId, gslJcId);
                //添加gsl_zw_info
                saveGslZwInfo(wxUserId, wxNewUserId, gslJcId);
                //添加gsl_zw_qy
                saveGslZwQy(wxUserId, wxNewUserId, gslJcId);
                //添加gsl_jc_zw
                int gcZwCount = saveGslJcZw(wxNewUserId, gslJcId);
                jcZwCount.add(gcZwCount);
            });
        }
        return saveGslJc(jsonObject, gslJcId, jcZwCount.size(), maps);
    }

    /** 添加wx_usr表数据 */
    public String saveWxUser(String wxUserId, String wxNewUserId, String gslJcId) {
        //获取执委用户信息
        String queryZwWxUserSql = "select * from wx_user where id = :id";
        Map<String, Object> zwWxUserParam = new HashMap<>();
        zwWxUserParam.put("id", wxUserId);
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(queryZwWxUserSql, zwWxUserParam);

        Map<String, Object> copy = maps.get(0);
        copy.put("gsl_session", gslJcId);
        copy.put("id", wxNewUserId);
        copy.put("update_by", BizUtil.cur().curUserId());
        copy.put("create_by", BizUtil.cur().curUserId());
        copy.put("update_date", new Date());
        copy.put("create_date", new Date());
        copy.put("del_flag", "0");
        copy.put("role_scope", "1");
        copy.put("parent_role_scope", "1");
        //封装新增的sql语句
        List<String> fields = new ArrayList<>();
        List<String> placeholders = new ArrayList<>();
        copy.forEach((k, v) -> {
            if (v != null) {
                fields.add(k);
                placeholders.add(":" + k);
            }
        });

        String sql = String.format("INSERT INTO wx_user (%s) VALUES (%s)",
                String.join(", ", fields),
                String.join(", ", placeholders)
        );
        int count = jdbcTemplate.update(sql, copy);
        if(count > 0) {
            return wxNewUserId;
        }
        return null;
    }

    /** 添加gsl_zw_info */
    public int saveGslZwInfo(String wxUserId, String wxNewUserId, String gslJcId) {
        String gslZwInfoId = BizUtil.cur().getSnowflakeIdStr();
        //获取执委用户信息
        String queryZwWxUserSql = "select * from gsl_zw_info where zw_id = :zw_id";
        Map<String, Object> zwWxUserParam = new HashMap<>();
        zwWxUserParam.put("zw_id", wxUserId);
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(queryZwWxUserSql, zwWxUserParam);

        Map<String, Object> copy = maps.get(0);
        copy.put("id", gslZwInfoId);
        copy.put("update_by", BizUtil.cur().curUserId());
        copy.put("create_by", BizUtil.cur().curUserId());
        copy.put("update_date", new Date());
        copy.put("create_date", new Date());
        copy.put("del_flag", "0");
        copy.put("zw_id", wxNewUserId);

        //封装新增的sql语句
        List<String> fields = new ArrayList<>();
        List<String> placeholders = new ArrayList<>();
        copy.forEach((k, v) -> {
            if (v != null) {
                fields.add(k);
                placeholders.add(":" + k);
            }
        });

        String sql = String.format("INSERT INTO gsl_zw_info (%s) VALUES (%s)",
                String.join(", ", fields),
                String.join(", ", placeholders)
        );
        return jdbcTemplate.update(sql, copy);
    }

    /** 添加gsl_zw_qy */
    public int saveGslZwQy(String wxUserId, String wxNewUserId, String gslJcId) {
        String id = BizUtil.cur().getSnowflakeIdStr();
        //获取执委用户信息
        String queryZwWxUserSql = "select * from gsl_zw_qy where zw_id = :zw_id";
        Map<String, Object> param = new HashMap<>();
        param.put("zw_id", wxUserId);
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(queryZwWxUserSql, param);

        Map<String, Object> copy = maps.get(0);
        copy.put("id", id);
        copy.put("update_by", BizUtil.cur().curUserId());
        copy.put("create_by", BizUtil.cur().curUserId());
        copy.put("update_date", new Date());
        copy.put("create_date", new Date());
        copy.put("del_flag", "0");
        copy.put("zw_id", wxNewUserId);

        //封装新增的sql语句
        List<String> fields = new ArrayList<>();
        List<String> placeholders = new ArrayList<>();
        copy.forEach((k, v) -> {
            if (v != null) {
                fields.add(k);
                placeholders.add(":" + k);
            }
        });

        String sql = String.format("INSERT INTO gsl_zw_qy (%s) VALUES (%s)",
                String.join(", ", fields),
                String.join(", ", placeholders)
        );
        return jdbcTemplate.update(sql, copy);
    }

    /** 添加gsl_jc_zw */
    public int saveGslJcZw(String wxNewUserId, String gslJcId) {
        String id = BizUtil.cur().getSnowflakeIdStr();
        Map<String, Object> copy = new HashMap<>();
        copy.put("id", id);
        copy.put("zw_id", wxNewUserId);
        copy.put("jc_id", gslJcId);
        copy.put("update_by", BizUtil.cur().curUserId());
        copy.put("create_by", BizUtil.cur().curUserId());
        copy.put("update_date", new Date());
        copy.put("create_date", new Date());
        copy.put("del_flag", "0");

        //封装新增的sql语句
        List<String> fields = new ArrayList<>();
        List<String> placeholders = new ArrayList<>();
        copy.forEach((k, v) -> {
            if (v != null) {
                fields.add(k);
                placeholders.add(":" + k);
            }
        });

        String sql = String.format("INSERT INTO gsl_jc_zw (%s) VALUES (%s)",
                String.join(", ", fields),
                String.join(", ", placeholders)
        );
        return jdbcTemplate.update(sql, copy);
    }

    /** 添加gsl_jc */
    public int saveGslJc(JSONObject jsonObject, String gslJcId, int jcZwCount, List<Map<String, Object>> maps) {
        Map<String, Object> copy = new HashMap<>();
        copy.put("id", gslJcId);
        copy.put("session", jsonObject.getString("session"));
        copy.put("start_year", jsonObject.getString("start_year"));
        copy.put("end_year", jsonObject.getString("end_year"));
        copy.put("executive_committee", jsonObject.getString("executive_committee"));
        copy.put("zw_count", jcZwCount);
        copy.put("role_scope", "1");
        copy.put("parent_role_scope", "1");
        copy.put("update_by", BizUtil.cur().curUserId());
        copy.put("create_by", BizUtil.cur().curUserId());
        copy.put("update_date", new Date());
        copy.put("create_date", new Date());
        copy.put("del_flag", "0");
        if(maps.isEmpty()) {
            //封装新增的sql语句
            List<String> fields = new ArrayList<>();
            List<String> placeholders = new ArrayList<>();
            copy.forEach((k, v) -> {
                if (v != null) {
                    fields.add(k);
                    placeholders.add(":" + k);
                }
            });
            String sql = String.format("INSERT INTO gsl_jc (%s) VALUES (%s)",
                    String.join(", ", fields),
                    String.join(", ", placeholders)
            );
            return jdbcTemplate.update(sql, copy);
        } else {
            List<String> fields = new ArrayList<>();
            copy.forEach((k, v) -> {
                if (v != null && !"id".equals(k)) {
                    fields.add(k + " = :" + k);
                }
            });

            String sql = String.format("UPDATE gsl_jc SET %s WHERE id = '%s'",
                    String.join(", ", fields),
                    copy.get("id")
            );
            return jdbcTemplate.update(sql, copy);
        }


    }
}
